package com.nikmesoft.android.referendumfriend.activities;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.AsyncTask.Status;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.nikmesoft.android.referendumfriend.R;
import com.nikmesoft.android.referendumfriend.models.Conver_MD5;
import com.nikmesoft.android.referendumfriend.models.User_register;
import com.nikmesoft.android.referendumfriend.service.Register_handler;
import com.nikmesoft.android.referendumfriend.utils.CommonUtil;

public class Login_register extends BaseActivity {
	private EditText ed1, ed3, ed4, ed5, ed6, ed7;
	private RadioButton rdfemale,rdmale;
	private EditText mDateDisplay;
	private Button mPickDate;
	private ProgressDialog dialog;
	private WSLoader loader;
	private int mYear;
	private int mMonth;
	private int mDay;
	static final int DATE_DIALOG_ID = 0;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_register);
		init();
	}

	private void init() {
		ed1 = (EditText) findViewById(R.id.register_edfullname);
		mDateDisplay = (EditText) findViewById(R.id.register_edbirthday);
		ed3 = (EditText) findViewById(R.id.register_edphone);
		ed4 = (EditText) findViewById(R.id.register_eduser);
		ed5 = (EditText) findViewById(R.id.register_edpass);
		ed6 = (EditText) findViewById(R.id.register_edconfirm);
		ed7 = (EditText) findViewById(R.id.register_edemail);
		rdfemale=(RadioButton)findViewById(R.id.next_rdfemale);
		rdmale=(RadioButton)findViewById(R.id.next_rdmale);
		
		mPickDate = (Button) findViewById(R.id.next_btday);

		dialog = new ProgressDialog(this);
		dialog.setMessage("Loading...Please wait...");
		
		// add a click listener to the button
		mPickDate.setOnClickListener(new View.OnClickListener() {
			@SuppressWarnings("deprecation")
			public void onClick(View v) {
				showDialog(DATE_DIALOG_ID);
			}
		});

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, 1991, 1, 1);
		}
		return null;
	}

	private void updateDisplay() {
		mDateDisplay.setText(new StringBuilder()
				// Month is 0 based so add 1
				.append(mMonth + 1).append("/").append(mDay).append("/")
				.append(mYear).append(" "));
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear = year;
			mMonth = monthOfYear;
			mDay = dayOfMonth;
			updateDisplay();
		}
	};

	public void Next_activity(View v) {
		
		if (ed1.getText().toString().equals("")
				|| mDateDisplay.getText().toString().equals("")
				|| ed3.getText().toString().equals("")
				|| ed4.getText().toString().equals("")
				|| ed5.getText().toString().equals("")
				|| ed6.getText().toString().equals("")
				|| ed7.getText().toString().equals("")) {
			CommonUtil.toastNotify(this,
					getString(R.string.msg_register_missinfor));
			return;
		}
		if (ed5.getText().toString().equals(ed6.getText().toString()) == false) {
			CommonUtil.toastNotify(this,
					getString(R.string.msg_register_confirmerro));
			return;
		}
		if (checkmail(ed7.getText().toString()) == false) {
			CommonUtil.toastNotify(this, getString(R.string.msg_register_mail));
			return;
		}
 
		
		int gen=0;
		if (rdfemale.isChecked()) gen=1;
		if (loader == null || loader.isCancelled()
				|| loader.getStatus() == Status.FINISHED) {
			loader = new WSLoader();
			String pass=ed5.getText().toString();
			pass=Conver_MD5.md5Digest(pass);
			loader.execute(ed1.getText().toString(),ed7.getText().toString(),ed4.getText().toString(),pass,
					mDateDisplay.getText().toString(),String.valueOf(gen),"Default",ed3.getText().toString(),"Default");
		}
		
	}
	public void Next_activities()
	{
		finish();
	}

	// kiem tra mail co hop le khong
	public boolean checkmail(String s) {
		char a;
		int t = 0;
		for (int i = 0; i < s.length() - 1; i++) {
			a = s.charAt(i);
			if (i == 0
					&& ((a > '9' || a < '0') && (a > 'z' || a < 'a') && (a > 'Z' || a < 'A')))
				return false;
			if (a != '@') {
				if (t == 0) {
					if ((a >= '0' && a <= '9') || (a >= 'a' && a <= 'z')
							|| (a >= 'A' && a <= 'Z') || a == '.' || a == '_')
						continue;
				} else {
					if ((a >= '0' && a <= '9') || (a >= 'a' && a <= 'z')
							|| (a >= 'A' && a <= 'Z') || a == '.')
						continue;
				}
			} else {
				if (t == 0)
					t++;
				else
					return false;
			}
		}
		if (t == 0)
			return false;
		return true;
	}
	
	private String callWS(String fullname, String email,String username,String password, String birthday,
			String gender,String address, String mobile, String facebook
			) {
		String body = "<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\">"
				+ "<soapenv:Header/><soapenv:Body>"
				+ "<register soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
				+ "<RegisterRequest xsi:type=\"rdf:RegisterRequest\" xmlns:rdf=\"http://nikmesoft.com/apis/RDFServices/\">"
	            
	            + "<fullname xsi:type=\"xsd:string\">"+fullname+"</fullname>"
	            + "<email xsi:type=\"xsd:string\">"+email+"</email>"
	            + "<username xsi:type=\"xsd:string\">"+username+"</username>"
	            + "<password xsi:type=\"xsd:string\">"+password+"</password>"
	            + "<birthday xsi:type=\"xsd:string\">"+birthday+"</birthday>"
	            + "<gender xsi:type=\"xsd:int\">"+gender+"</gender>"
	            + "<address xsi:type=\"xsd:string\">"+address+"</address>"
	            + "<mobile xsi:type=\"xsd:string\">"+mobile+"</mobile>"
	            + "<facebook xsi:type=\"xsd:string\">"+facebook+"</facebook>"
	         + "</RegisterRequest>"
	      +   "</register>"
	   + 		"</soapenv:Body>"
       +	"</soapenv:Envelope>";

		final DefaultHttpClient httpClient = new DefaultHttpClient();
		// request parameters
		HttpParams params = httpClient.getParams();
		HttpConnectionParams.setConnectionTimeout(params, 10000);
		HttpConnectionParams.setSoTimeout(params, 15000);
		// set parameter
		HttpProtocolParams.setUseExpectContinue(httpClient.getParams(), true);

		// POST the envelope
		HttpPost httppost = new HttpPost(
				"http://nikmesoft.com/apis/RDFServices/index.php");
		// add headers
		httppost.setHeader("SoapAction",
				"http://nikmesoft.com/apis/RDFServices/index.php/");
		httppost.setHeader("Content-Type", "text/xml; charset=utf-8");

		String responseString = "";
		try {

			// the entity holds the request
			HttpEntity entity = new StringEntity(body);
			httppost.setEntity(entity);

			// Response handler
			ResponseHandler<String> rh = new ResponseHandler<String>() {
				// invoked when client receives response
				public String handleResponse(HttpResponse response)
						throws ClientProtocolException, IOException {

					// get response entity
					HttpEntity entity = response.getEntity();

					// read the response as byte array
					StringBuffer out = new StringBuffer();
					byte[] b = EntityUtils.toByteArray(entity);

					// write the response byte array to a string buffer
					out.append(new String(b, 0, b.length));
					return out.toString();
				}
			};

			responseString = httpClient.execute(httppost, rh);

		} catch (Exception e) {
			Log.v("Exception", e.toString());
		}

		// close the connection
		httpClient.getConnectionManager().shutdown();
		Log.i("Webservice", responseString);
		return responseString;
	}

	private User_register xmlParser(String strXml) {
		byte xmlBytes[] = strXml.getBytes();
		ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
				xmlBytes);
		SAXParserFactory saxPF = SAXParserFactory.newInstance();
		SAXParser saxParser;
		try {
			saxParser = saxPF.newSAXParser();
			XMLReader xr = saxParser.getXMLReader();
			Register_handler handler = new Register_handler();
			xr.setContentHandler(handler);
			xr.parse(new InputSource(byteArrayInputStream));
			return handler.getResult();

		} catch (ParserConfigurationException ex) {
			ex.printStackTrace();
		} catch (SAXException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		return null;
	}

	private class WSLoader extends AsyncTask<String, Integer, User_register> {

		@Override
		protected User_register doInBackground(String... params) {
			return xmlParser(callWS(params[0], params[1],params[2],params[3],
					params[4],params[5],params[6],params[7],params[8]));
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
		}

		@Override
		protected void onPostExecute(User_register result) {
			super.onPostExecute(result);
			
			if (result.getError()!= null) toad(result.getError().getErrorMsg());
			else Next_activities();
			dialog.dismiss();
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog.show();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {
			super.onProgressUpdate(values);
		}

	}
	public void toad(String str){
		CommonUtil.toastNotify(this,str);
	}
}
